import { useEffect, useRef, useState } from "react"
import { AppViewResource } from "@/global"
import AppConstant from "@/services/common/AppConstant"
import { fetchUserInfo, fetchViewResource, ViewResourceResponse } from "@/services/auth/auth"
import { AppConsumerFunction } from "@/services/common/functioninterface"

export interface UseAuthCallbackProp {
  isLogin?: boolean,
  authUser?: any
  viewResourceResponse?: ViewResourceResponse | null
}

export interface UserAuthProp {
  jumpToHome?: boolean,
  loadFinishedCallback?: AppConsumerFunction<UseAuthCallbackProp>
}

export interface AuthUser {
  // 用户信息
  user?: any
  // 视图资源信息
  viewResource?: AppViewResource[]
}

/**
 * hook逻辑复用。
 * TODO 优化。多个组件中都使用这个hook,会导致多个地方重复请求用户信息，看下是否需要优化下。
 */

export default function useAuth(prop: UserAuthProp = {
  jumpToHome: true,
  loadFinishedCallback: () => {}
}) {
  const authUserRef = useRef<any>(null)
  const viewResourceResponseRef = useRef<ViewResourceResponse | null>(null)
  const isLoginRef = useRef<boolean>(false);

  const [authUser, setAuthUser] = useState<any>(null)
  const [viewResourceResponse, setViewResourceResponse] = useState<ViewResourceResponse>()

  const loadUserInfo = async () => {
    const userInfo = await fetchUserInfo();
    if (userInfo) {
      authUserRef.current = userInfo
      setAuthUser(userInfo)
      isLoginRef.current = true
    } else {
      isLoginRef.current = false
    }
  }

  /**
   * 
   */
  const loadUserViewResource = async () => {
    const resp = await fetchViewResource();
    if (resp) {
      viewResourceResponseRef.current = resp
      setViewResourceResponse(resp)
    }
  }

  const loadUserAllData = async () => {
    return Promise.all([loadUserInfo(), loadUserViewResource()])
  }

  useEffect(() => {
    // 没有token，肯定没登录
    if (!window.localStorage.getItem(AppConstant.localStroageTokenKey)) {
      isLoginRef.current = false;
      prop.loadFinishedCallback?.({isLogin: isLoginRef.current, authUser: authUserRef.current,
        viewResourceResponse: viewResourceResponseRef.current})
    } else {
      loadUserAllData().then(() => {
        prop.loadFinishedCallback?.({isLogin: isLoginRef.current, authUser: authUserRef.current,
           viewResourceResponse: viewResourceResponseRef.current})
      })
    }
  }, [])
  
  return {
    authUser,
    viewResourceResponse
  }
}